package com.zmn.uac.util;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.uac.common.constant.AlibabaLogConstant;
import com.zmn.uac.common.dio.oauth.login.UserAuthLoginDIO;
import com.zmn.uac.common.dro.oauth.login.UserAuthLoginDRO;
import com.zmn.uac.common.dro.oauth.login.UserInfoDRO;
import com.zmn.uac.common.entity.oauth.login.PlatInfo;
import com.zmn.uac.common.entity.oauth.login.ThirdAppInfo;
import com.zmn.uac.common.entity.oauth.login.UserInfo;
import com.zmn.uac.common.entity.oauth.phone.UserPhoneInfo;
import com.zmn.uac.common.info.UserAuthPhoneInfo;
import com.zmn.uac.common.info.baidu.BaiduUserAuthPhoneInfo;
import com.zmn.uac.common.info.mobile.MobileUserAuthInfo;
import com.zmn.uuc.common.dio.integrate.UserRegisterMobileAndLoginByUserIdDIO;
import com.zmn.uuc.common.dio.pass.UserMobileLoginDIO;
import com.zmn.uuc.common.dro.user.UserThirdBaseDRO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 阿里巴巴日志接入
 */
@Slf4j
public class LogAlibabaUtil {
    private static OkHttpClient HTTP_CLIENT;

    static {
         HTTP_CLIENT = new OkHttpClient().newBuilder()
                .connectTimeout(2, TimeUnit.SECONDS)
                .callTimeout(2, TimeUnit.SECONDS)
                .pingInterval(2, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(2, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(32, 5, TimeUnit.MINUTES))
                .build();
    }

    public static void loginLog(UserInfoDRO data, UserAuthLoginDIO authLoginDIO, String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            log.error("DeviceId is null");
            return;
        }
        LogInfo log = new LogInfo();
        log.setDeviceid(deviceId);
        log.setOpenid("");
        log.setUnionid("");
        log.setPlat("");
        log.setChannelid(authLoginDIO.getChannelId() + "");
        log.setChannelname(authLoginDIO.getChannelName() + "");
        log.setShopid("");
        log.setEntrance("");
        log.setAppid("");
        log.setAppname("H5登录");
        log.setMobile("");
        log.setUserid(data.getUserId() + "");
        log.setPassid("");
        send(log);
    }

    public static void loginLog(UserAuthLoginDIO requestDio, UserInfo userInfo, PlatInfo platInfo, ThirdAppInfo thirdAppInfo, UserPhoneInfo userPhoneInfo, UserAuthLoginDRO userAuthLogin, UserThirdBaseDRO thirdBase, UserAuthPhoneInfo authPhoneInfo) {
        Map<String, Object> map = BeanMapper.objectToMap(authPhoneInfo);
        String deviceId = (map.get("deviceId") == null) ? "" : map.get("deviceId") + "";
        if (StringUtils.isEmpty(deviceId)) {
            log.error("DeviceId is null");
            return;
        }
        try {
            LogInfo loginfo = new LogInfo();
            loginfo.setDeviceid(deviceId);
            loginfo.setOpenid(requestDio.getOpenId());
            loginfo.setUnionid(userInfo.getUnionId() + "");
            loginfo.setPlat(platInfo.getPlat() + "");
            loginfo.setChannelid(requestDio.getChannelId() + "");
            loginfo.setChannelname(requestDio.getChannelName() + "");
            loginfo.setShopid(requestDio.getShopId() + "");
            loginfo.setEntrance(requestDio.getEntrance() + "");
            loginfo.setAppid(thirdAppInfo.getAppId() + "");
            loginfo.setAppname(thirdAppInfo.getAppName());
            loginfo.setMobile(userPhoneInfo.getMobile());
            loginfo.setUserid(userAuthLogin.getUserId() + "");
            if (thirdBase != null) {
                loginfo.setPassid(thirdBase.getPassId() + "");
            }
            send(loginfo);
        } catch (Exception e) {
            log.error("系统异常", e);
        }
    }

    public static void loginLog(UserAuthLoginDIO userAuthLoginDIO, UserAuthLoginDRO userAuthLoginDRO, String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            log.error("DeviceId is null");
            return;
        }
        LogInfo log = new LogInfo();
        log.setDeviceid(deviceId);
        log.setOpenid("");
        log.setUnionid("");
        log.setPlat("");
        log.setChannelid(userAuthLoginDIO.getChannelId() + "");
        log.setChannelname(userAuthLoginDIO.getChannelName() + "");
        log.setShopid("");
        log.setEntrance("");
        log.setAppid("");
        log.setAppname(userAuthLoginDIO.getAppName());
        log.setMobile("");
        log.setUserid(userAuthLoginDRO.getUserId() + "");
        log.setPassid("");
        send(log);

    }

    public static void loginLog(UserAuthLoginDRO userAuthLoginDRO, UserAuthPhoneInfo authPhoneInfo, UserRegisterMobileAndLoginByUserIdDIO loginByUserIdDIO, Long passId) {
        Map<String, Object> map = BeanMapper.objectToMap(authPhoneInfo);
        String deviceId = (map.get("deviceId") == null) ? "" : map.get("deviceId") + "";
        if (StringUtils.isEmpty(deviceId)) {
            log.error("DeviceId is null");
            return;
        }
        try {
            LogInfo loginfo = new LogInfo();
            loginfo.setDeviceid(deviceId);
            loginfo.setOpenid(null);
            loginfo.setUnionid(null);
            loginfo.setPlat(loginByUserIdDIO.getPlat() + "");
            loginfo.setChannelid(loginByUserIdDIO.getChannelId() + "");
            loginfo.setChannelname(loginByUserIdDIO.getChannelName() + "");
            loginfo.setShopid("");
            loginfo.setEntrance(loginByUserIdDIO.getEntrance() + "");
            loginfo.setAppid("");
            loginfo.setAppname("");
            loginfo.setMobile(loginByUserIdDIO.getMobile());
            loginfo.setUserid(userAuthLoginDRO.getUserId() + "");
            loginfo.setPassid(passId + "");
            send(loginfo);
        } catch (Exception e) {
            log.error("系统异常", e);
        }
    }

    public static void mobileLoginLog(UserAuthLoginDRO userAuthLoginDRO, UserAuthPhoneInfo authPhoneInfo, UserMobileLoginDIO mobileLogin, MobileUserAuthInfo authInfo) {
        Map<String, Object> map = BeanMapper.objectToMap(authPhoneInfo);
        String deviceId = (map.get("deviceId") == null) ? "" : map.get("deviceId") + "";
        if (StringUtils.isEmpty(deviceId)) {
            log.error("DeviceId is null");
            return;
        }
        try {
            LogInfo loginfo = new LogInfo();
            loginfo.setDeviceid(deviceId);
            loginfo.setOpenid(authInfo.getOpenid());
            loginfo.setUnionid(null);
            loginfo.setPlat(mobileLogin.getPlat() + "");
            loginfo.setChannelid(mobileLogin.getChannelId() + "");
            loginfo.setChannelname(mobileLogin.getChannelName() + "");
            loginfo.setShopid("");
            loginfo.setEntrance(mobileLogin.getEntrance() + "");
            loginfo.setAppid("");
            loginfo.setAppname("");
            loginfo.setMobile(mobileLogin.getMobile());
            loginfo.setUserid(userAuthLoginDRO.getUserId() + "");
            loginfo.setPassid("");
            send(loginfo);
        } catch (Exception e) {
            log.error("系统异常", e);
        }
    }

    private static void send(LogInfo logInfo) {

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("__topic__", "user_login_log");
            params.put("__source__", "user_login_log");
            params.put("__logs__", Arrays.asList(logInfo));
            String jsonString = JSON.toJSONString(params);

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
            Request build = new Request.Builder()
                    .header("x-log-apiversion", "0.6.0")
                    .url(URI.create(AlibabaLogConstant.USER_LOGIN_LOG).toURL()).post(requestBody).build();
            Call call = HTTP_CLIENT.newCall(build);
            log.info("用阿里日志接入参数开始:{}", jsonString);
            Response execute = call.execute();
            String response = execute.body().string();

            if (!execute.isSuccessful()) {
                log.error("用阿里日志接入-失败1={}", response);
            } else {
                log.info("用阿里日志接入参数完成:{}", jsonString);
            }
        } catch (Exception e) {
            log.error("用阿里日志接入-失败2",e);
        }
    }

    @Data
    public static class LogInfo {
        private String deviceid;
        private String openid;
        private String unionid;
        private String plat;
        private String channelid;
        private String channelname;
        private String shopid;
        private String entrance;
        private String appid;
        private String appname;
        private String mobile;
        private String userid;
        private String passid;
    }

    public static void main(String[] args) {
        LogInfo logInfo = new LogInfo();
        logInfo.setDeviceid("setDeviceid");
        logInfo.setOpenid("setOpenid");
        logInfo.setUnionid("setUnionid");
        logInfo.setPlat("setPlat");
        logInfo.setChannelid("setChannelid");
        logInfo.setChannelname("setChannelname");
        logInfo.setShopid("setShopid");
        logInfo.setEntrance("setEntrance");
        logInfo.setAppid("setAppid");
        logInfo.setAppname("setAppname");
        logInfo.setMobile("setMobile");
        logInfo.setUserid("setUserid");
        logInfo.setPassid("setPassid");
        send(logInfo);
    }
}
